package info.johnwheeler.gaestorage.servlet;

import info.johnwheeler.gaestorage.core.Document;
import info.johnwheeler.gaestorage.core.DocumentDao;
import info.johnwheeler.gaestorage.core.Person;
import info.johnwheeler.gaestorage.core.PersonDao;
import info.johnwheeler.gaestorage.resources.Event;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import com.google.appengine.api.oauth.OAuthRequestException;
import com.google.appengine.api.oauth.OAuthService;
import com.google.appengine.api.oauth.OAuthServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Key;

@SuppressWarnings("serial")
public class DocumentServlet extends AbstractUploadServlet {
    private DocumentDao dao = new DocumentDao();
    private PersonDao personDao = new PersonDao();

    @Override
    protected void showForm(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        String url = "";
        int event;

        if (user == null)
        	event = Event.OAUTH;
        else event = Event.SELECT;
        
        switch (event){
        case Event.OAUTH:
        	url = userService.createLoginURL(req.getRequestURI());
        	resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
        	break;
        case Event.SELECT:
        	url = "document.jsp";
        	Long idDocument = (long) 0;
        	try{
        		idDocument = Long.parseLong(req.getParameter("idDocument"));
        	} catch (Exception e){
        		
        	}
        	try{
        		event = Integer.parseInt(req.getParameter("event"));
        	} catch (Exception e){
        		
        	}
        	if(idDocument!=0){
        		Document document = dao.findById(idDocument);
        		dao.populatePersons(document);
        		req.setAttribute("documentFilter", document);
        	}
        	
        	//Lista dos documentos
        	ArrayList<Document> documents = dao.findAll();
            req.setAttribute("documents", documents);
            
            //Lista de pessoas. Popula os dados das pessoas cadastradas 
            //pra vincular com documento
            ArrayList<Person> people = personDao.findAll();   
            req.setAttribute("people", people);
            req.getRequestDispatcher("document.jsp").forward(req, resp); 
        	break;
        	
        }
        
    	       
    }

    @Override
    protected void handleSubmit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletFileUpload upload = new ServletFileUpload();

        try {
            FileItemIterator it = upload.getItemIterator(req);

            Document document = new Document();

            while (it.hasNext()) {
                FileItemStream item = it.next();
                String fieldName = item.getFieldName();
                InputStream fieldValue = item.openStream();

                if ("title".equals(fieldName)) {
                    document.setTitle(Streams.asString(fieldValue));
                    continue;
                }

                if ("caption".equals(fieldName)) {
                	document.setCaption(Streams.asString(fieldValue));
                    continue;
                }
                
                if("processNumber".equals(fieldName)){
                	document.setProcessNumber(Streams.asString(fieldValue));
                	continue;
                }
                
                if("author".equals(fieldName)){
                	String id = (Streams.asString(fieldValue));
                	Key<Person> key = new Key<Person>(Person.class, id);
                	document.setAuthorKey(key);
                	continue;
                }
                
                if("mapaddress".equals(fieldName)){
                	document.setCounty(Streams.asString(fieldValue));
                	continue;
                }
                if("deadLine".equals(fieldName)){
                	System.out.println(Streams.asString(fieldValue));
                	SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");  
                	//Date date = format.parse(Streams.asString(fieldValue));  
                	//document.setDeadLine(date);
                	continue;
                }
                if("description".equals(fieldName)){
                	document.setDescription(Streams.asString(fieldValue));
                	continue;
                }
                
                if("solicitationOwner".equals(fieldName)){
                	String id = (Streams.asString(fieldValue));
                	Key<Person> key = new Key<Person>(Person.class, id);
                	document.setSolicitationOwnerKey(key);
                	continue;
                }
                
                if ("file".equals(fieldName)) {
                	document.setContentType(item.getContentType());
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    Streams.copy(fieldValue, out, true);
                    document.setDocumentData(out.toByteArray());
                    continue;
                }
            }

            dao.save(document);
            try {
				sendMail(document);
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            resp.sendRedirect("document?action=display&id=" + document.getId());            
        } catch (FileUploadException e) {
            throw new ServletException(e);
        } /*catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   */     
    }

    @Override
    protected void showRecord(long id, HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Document document = dao.findById(id);
        
        resp.setContentType(document.getContentType());        
        resp.getOutputStream().write(document.getDocumentData());
        resp.flushBuffer();                    
    }
    
    public void sendMail(Document document) throws UnsupportedEncodingException, javax.mail.MessagingException{
    	Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        String msgBody = "...";

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("lbotton@gmail.com", "Example.com Admin"));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress("lbotton@gmail.com", "Mr. User"));
            msg.setSubject("Your Example.com account has been activated");
            msg.setText(msgBody + document.getDocumentPath());
            Transport.send(msg);
    
        } catch (AddressException e) {
            // ...
        } 
    }
}
